package com.cachemanage.service;

import com.cachemanage.dao.BookDao;
import com.cachemanage.pojo.Book;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import lombok.val;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class BookService {
	@Resource
	private BookDao bookDao;
	public List<Book> findAllBooks(){
		return bookDao.findAll();
	}
	@Cacheable(value = "book",key="#id")
	public Book findBookById(Integer id){
		System.out.println("从数据库中查找id为" + id + "的书籍，并添加到缓存，key为" + id);
		return bookDao.findById(id).orElse(new Book());
	}
	@CachePut(value = "book",key="#book.id")
	public Book addBook(Book book){
		System.out.println("将一本书添加到数据库，同时添加到缓存");
		return bookDao.save(book);
	}
	@CacheEvict(value = "book",key="#id")
	public void deleteBook(Integer id){
		System.out.println("从数据库删除一本书，同时删除key为" + id + "的缓存");
		bookDao.deleteById(id);
	}
	@CachePut(value = "book",key = "#book.id")
	public Book updateBook(Book book){
		System.out.println("从数据库修改一本书，同时修改缓存，key为" + book.getId() + "的缓存");
		return bookDao.save(book);
	}
	//@Cacheable(value = "books",key = "(#book.name!=null?#book.name:'')+(#book.category!=null?#book.category:'')+(#book.author!=null?#book.author:'')")
	@Cacheable(value = "books",keyGenerator = "bookSearchGenerator")
	public List<Book> searchBooks(Book book){
		System.out.println("条件查询，并添加到缓存，key为搜索条件的组合");
		System.out.println("book：" + book);
		return findAll(book);
	}
	public List<Book> findAll(Book book){
		Specification<Book> spec=new Specification<Book>() {
			@Override
			public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> predicates = new ArrayList<>();
				if (book.getName()!=null&&book.getName()!="") {
					System.out.println("root.get(\"name\")："+root.get("name").as(String.class));
					predicates.add(criteriaBuilder.like(root.get("name").as(String.class),"%"+book.getName()+"%"));
				}
				if (book.getCategory()!=null&&book.getCategory()!="") {
					predicates.add(criteriaBuilder.equal(root.get("category").as(String.class),book.getCategory()));
				}
				if (book.getAuthor()!=null&&book.getAuthor()!="") {
					predicates.add(criteriaBuilder.equal(root.get("author").as(String.class),"%"+book.getAuthor()+"%"));
				}
				return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};
		return bookDao.findAll(spec);
	}
}
